﻿#include "SuspendedSearchBox.h"
#include "CodeEditor.h"
#include <QPainter>
#include <QPainterPath>
#include <QPen>
#include <QBrush>
#include <QCloseEvent>
#include <QApplication>
#include <QScreen>
#include <QKeyEvent>
#include <QCursor>
#include "SearchService.h"
#include <QMessageBox>
#include "ThemeManager.h"

SuspendedSearchBox::SuspendedSearchBox(CodeEditor* parentEditor, QWidget* parent)
    : QWidget(parent)
    , m_parentEditor(parentEditor)
    , m_isDragging(false)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
    // 关键修改：启用透明背景，这样窗口本身就是透明的，我们在paintEvent中绘制的圆角背景才是真正的背景
    setAttribute(Qt::WA_TranslucentBackground, true);
    setFixedSize(380 + m_windowMargin * 2, 80 + m_windowMargin * 2);

    m_titleBarRect = QRect(m_contentMargin, m_contentMargin,
        width() - m_contentMargin * 2, m_titleBarHeight );

    // 1. 创建标题栏关闭按钮
    m_closeButton = new QPushButton("×", this);
    m_closeButton->setFixedSize(20, 20);
    connect(m_closeButton, &QPushButton::clicked, this, &SuspendedSearchBox::onCloseButtonClicked);

    // 2. 创建内容区域控件
    m_contentWidget = new QWidget(this);
    m_contentWidget->setGeometry(0, m_titleBarHeight, width(), height() - m_titleBarHeight);
    // 设置内容区域为透明背景（重要：避免遮挡paintEvent中绘制的圆角背景）
    m_contentWidget->setAttribute(Qt::WA_TranslucentBackground);
    m_contentWidget->setStyleSheet("background: transparent;");

    QHBoxLayout* mainLayout = new QHBoxLayout(m_contentWidget);
    mainLayout->setContentsMargins(5, 5, 5, 5);
    mainLayout->setSpacing(6);

    m_searchEdit = new QLineEdit(m_contentWidget);
    m_searchEdit->setPlaceholderText("输入查找内容...");
    m_searchEdit->setFixedHeight(34);

    connect(m_searchEdit, &QLineEdit::textChanged, this, [this](const QString& text) {
        if (text.trimmed().isEmpty()) {
            hideResults();
        }
        });

    m_modeCombo = new QComboBox(m_contentWidget);
    m_modeCombo->addItem("当前文件", QVariant::fromValue(FindMode::CurrentItem));
    m_modeCombo->addItem("所有最近文件", QVariant::fromValue(FindMode::AllRecentItems));
    m_modeCombo->setFixedHeight(34);

    m_findButton = new QPushButton("🔍", m_contentWidget);
    m_findButton->setToolTip("查找");
    m_findButton->setFixedHeight(34);

    mainLayout->addWidget(m_searchEdit, 1);
    mainLayout->addWidget(m_modeCombo);
    mainLayout->addWidget(m_findButton);

    // 3. 连接信号
    connect(m_findButton, &QPushButton::clicked, this, &SuspendedSearchBox::onFindButtonClicked);
    connect(m_modeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &SuspendedSearchBox::onFindModeChanged);

    // 4. 初始位置
    if (m_parentEditor) {
        QPoint editorTopRight = m_parentEditor->mapToGlobal(m_parentEditor->rect().topRight());
        move(editorTopRight.x() - width() - 10, editorTopRight.y() + 10);
    }

    // 创建搜索结果列表
    m_resultList = new SearchResultList(this);
    m_resultList->setGeometry(0, 80, width(), 300);
    m_resultList->hide();

    // 连接SearchService
    SearchService::GetInstance()->setSearchResultList(m_resultList);
    connect(SearchService::GetInstance().get(), &SearchService::contentSearchCompleted,
        this, &SuspendedSearchBox::onContentSearchCompleted);

    // ===== 主题适配 =====
    // 连接主题变化信号
    connect(&ThemeManager::GetInstance(), &ThemeManager::themeChanged,
        this, &SuspendedSearchBox::onThemeChanged);

    // 应用当前主题
    applyCurrentTheme();
}

void SuspendedSearchBox::applyCurrentTheme()
{
    ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
    if (currentTheme == ThemeManager::Theme::Dark) {
        applyDarkTheme();
    }
    else {
        applyLightTheme();
    }
}

void SuspendedSearchBox::applyLightTheme()
{
    // 关闭按钮浅色主题
    m_closeButton->setStyleSheet(R"(
        QPushButton {
            color: #666;
            background: transparent;
            border: none;
            border-radius: 2px;
        }
        QPushButton:hover {
            background: #ff4444;
            color: white;
        }
    )");

    // 搜索框浅色主题
    m_searchEdit->setStyleSheet(R"(
        QLineEdit {
            border: 1px solid #CCCCCC;
            border-radius: 4px;
            padding: 0 8px;
            background: white;
            color: #24292E;
            font-size: 15px;
        }
        QLineEdit:focus {
            border-color: #4A90E2;
            outline: none;
        }
    )");

    // 下拉框浅色主题
    m_modeCombo->setStyleSheet(R"(
        QComboBox {
            border: 1px solid #CCCCCC;
            border-radius: 4px;
            padding: 0 8px;
            background: white;
            color: #24292E;
            font-size: 15px;
            min-width: 100px;
        }
        QComboBox::drop-down {
            border: none;
        }
        QComboBox QAbstractItemView {
            border: 1px solid #CCCCCC;
            border-radius: 4px;
            background: white;
            color: #24292E;
            selection-background-color: #4A90E2;
            selection-color: white;
            outline: none;
            font-size: 15px;
        }
        QComboBox QAbstractItemView::item {
            height: 28px;
            padding: 0 8px;
        }
    )");

    // 查找按钮浅色主题
    m_findButton->setStyleSheet(R"(
        QPushButton {
            border: 1px solid #CCCCCC;
            border-radius: 4px;
            padding: 0 8px;
            background: #f0f0f0;
            color: #24292E;
        }
        QPushButton:hover {
            background: #e0e0e0;
        }
        QPushButton:pressed {
            background: #d0d0d0;
        }
    )");

    // 触发重绘以更新标题栏和窗口背景颜色
    update();
}

void SuspendedSearchBox::applyDarkTheme()
{
    // 关闭按钮深色主题
    m_closeButton->setStyleSheet(R"(
        QPushButton {
            color: #CCCCCC;
            background: transparent;
            border: none;
            border-radius: 2px;
        }
        QPushButton:hover {
            background: #ff4444;
            color: white;
        }
    )");

    // 搜索框深色主题
    m_searchEdit->setStyleSheet(R"(
        QLineEdit {
            border: 1px solid #464647;
            border-radius: 4px;
            padding: 0 8px;
            background: #3C3C3C;
            color: #E8E8E8;
            font-size: 15px;
        }
        QLineEdit:focus {
            border-color: #4A90E2;
            outline: none;
        }
    )");

    // 下拉框深色主题
    m_modeCombo->setStyleSheet(R"(
        QComboBox {
            border: 1px solid #464647;
            border-radius: 4px;
            padding: 0 8px;
            background: #3C3C3C;
            color: #E8E8E8;
            font-size: 15px;
            min-width: 100px;
        }
        QComboBox::drop-down {
            border: none;
        }
        QComboBox QAbstractItemView {
            border: 1px solid #464647;
            border-radius: 4px;
            background: #2D2D30;
            color: #E8E8E8;
            selection-background-color: #4A90E2;
            selection-color: white;
            outline: none;
            font-size: 15px;
        }
        QComboBox QAbstractItemView::item {
            height: 28px;
            padding: 0 8px;
        }
    )");

    // 查找按钮深色主题
    m_findButton->setStyleSheet(R"(
        QPushButton {
            border: 1px solid #464647;
            border-radius: 4px;
            padding: 0 8px;
            background: #3C3C3C;
            color: #E8E8E8;
        }
        QPushButton:hover {
            background: #464647;
        }
        QPushButton:pressed {
            background: #4E4E52;
        }
    )");

    // 触发重绘以更新标题栏和窗口背景颜色
    update();
}

void SuspendedSearchBox::onThemeChanged(ThemeManager::Theme newTheme)
{
    if (newTheme == ThemeManager::Theme::Dark) {
        applyDarkTheme();
    }
    else {
        applyLightTheme();
    }
}

void SuspendedSearchBox::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);  // 抗锯齿，让圆角更平滑

    ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();

    // 定义圆角半径
    const int borderRadius = 8;

    if (currentTheme == ThemeManager::Theme::Dark) {
        // ===== 深色主题 =====
        // 1. 绘制整个窗口的圆角背景和边框
        QPainterPath windowPath;
        windowPath.addRoundedRect(rect(), borderRadius, borderRadius);

        // 绘制边框
        painter.setPen(QPen(QColor(62, 62, 66), 1));
        painter.setBrush(QColor(30, 30, 30));  // 窗口主背景色
        painter.drawPath(windowPath);

        // 2. 绘制标题栏背景（上半部分圆角，下半部分直角）
        //QPainterPath titleBarPath;
        //// 先添加一个顶部圆角矩形
        //QRectF titleRect(0, 0, width(), m_titleBarHeight);
        //titleBarPath.addRoundedRect(titleRect, borderRadius, borderRadius);
        //// 然后添加一个底部直角矩形来"切掉"标题栏底部的圆角
        //QRectF bottomRect(0, m_titleBarHeight - borderRadius, width(), borderRadius);
        //titleBarPath.addRect(bottomRect);

        //painter.setPen(Qt::NoPen);
        //painter.setBrush(QColor(45, 45, 48));  // 标题栏背景色
        //painter.drawPath(titleBarPath);

        // 3. 绘制标题文字
        painter.setPen(QColor(200, 200, 200));
        QFont font = painter.font();
        font.setUnderline(false);  // 确保文字没有下划线
        painter.setFont(font);
        painter.drawText(QRect(10, 0, width() - 40, m_titleBarHeight),
            Qt::AlignVCenter | Qt::AlignLeft, "查找");

        // 4. 绘制标题栏底部分隔线
        painter.setPen(QPen(QColor(62, 62, 66), 1));
        painter.drawLine(0, m_titleBarHeight, width(), m_titleBarHeight);
    }
    else {
        // ===== 浅色主题 =====
        // 1. 绘制整个窗口的圆角背景和边框
        QPainterPath windowPath;
        windowPath.addRoundedRect(rect(), borderRadius, borderRadius);

        // 绘制边框
        painter.setPen(QPen(QColor(220, 220, 220), 1));
        painter.setBrush(QColor(255, 255, 255));  // 窗口主背景色
        painter.drawPath(windowPath);

        //// 2. 绘制标题栏背景（上半部分圆角，下半部分直角）
        //QPainterPath titleBarPath;
        //QRectF titleRect(0, 0, width(), m_titleBarHeight);
        //titleBarPath.addRoundedRect(titleRect, borderRadius, borderRadius);
        //QRectF bottomRect(0, m_titleBarHeight - borderRadius, width(), borderRadius);
        //titleBarPath.addRect(bottomRect);

        //painter.setPen(Qt::NoPen);
        //painter.setBrush(QColor(245, 245, 245));  // 标题栏背景色
        //painter.drawPath(titleBarPath);

        // 3. 绘制标题栏底部分隔线
        painter.setPen(QPen(QColor(200, 200, 200), 1));
        painter.drawLine(0, m_titleBarHeight, width(), m_titleBarHeight);

        // 4. 绘制标题文字
        painter.setPen(QColor(100, 100, 100));
        QFont font = painter.font();
        font.setUnderline(false);  // 确保文字没有下划线
        painter.setFont(font);
        painter.drawText(QRect(10, 0, width() - 40, m_titleBarHeight),
            Qt::AlignVCenter | Qt::AlignLeft, "查找");
    }
}

// 其余方法保持不变
void SuspendedSearchBox::resizeEvent(QResizeEvent* event)
{
    m_titleBarRect.setWidth(width());
    m_closeButton->move(width() - 24, 2);
    QWidget::resizeEvent(event);
}

void SuspendedSearchBox::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        if (m_titleBarRect.contains(event->pos()) &&
            !m_closeButton->geometry().contains(event->pos())) {
            m_dragStartPos = event->pos();
            m_isDragging = true;
            setCursor(QCursor(Qt::ClosedHandCursor));
            event->accept();
        }
        else {
            m_isDragging = false;
            QWidget::mousePressEvent(event);
        }
    }
    else {
        QWidget::mousePressEvent(event);
    }
}

void SuspendedSearchBox::mouseMoveEvent(QMouseEvent* event)
{
    if (m_isDragging && (event->buttons() & Qt::LeftButton)) {
        QPoint newPos = event->globalPos() - m_dragStartPos;
        move(newPos);
        event->accept();
    }
    else {
        QWidget::mouseMoveEvent(event);
    }
}

void SuspendedSearchBox::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton && m_isDragging) {
        m_isDragging = false;
        setCursor(QCursor(Qt::ArrowCursor));
        snapToEditorEdge();
        event->accept();
    }
    else {
        QWidget::mouseReleaseEvent(event);
    }
}

void SuspendedSearchBox::keyPressEvent(QKeyEvent* event)
{
    if ((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && m_searchEdit->hasFocus()) {
        onFindButtonClicked();
        event->accept();
    }
    else {
        QWidget::keyPressEvent(event);
    }
}

void SuspendedSearchBox::onFindButtonClicked()
{
    QString searchText = m_searchEdit->text().trimmed();
    if (!searchText.isEmpty()) {
        SearchService::GetInstance()->onSearchTriggered(searchText, getCurrentFindMode());
        m_searchEdit->setFocus();
    }
}

void SuspendedSearchBox::onFindModeChanged(int index)
{
    Q_UNUSED(index);
    snapToEditorEdge();
}

void SuspendedSearchBox::snapToEditorEdge()
{
    if (!m_parentEditor) return;

    QRect editorRect = m_parentEditor->frameGeometry();
    QRect currentRect = frameGeometry();
    QPoint newPos = currentRect.topLeft();

    if (qAbs(currentRect.left() - editorRect.right()) <= m_snapDistance) {
        newPos.setX(editorRect.right());
    }
    if (qAbs(currentRect.top() - editorRect.top()) <= m_snapDistance) {
        newPos.setY(editorRect.top());
    }

    if (newPos != currentRect.topLeft()) {
        move(newPos);
    }
}

void SuspendedSearchBox::onCloseButtonClicked()
{
    hideSearchBox();
}

void SuspendedSearchBox::onContentSearchCompleted(int count, bool isMultiFile)
{
    Q_UNUSED(isMultiFile);
    if (count > 0) {
        showResults();
    }
    else {
        hideResults();
        QMessageBox::information(this, "搜索结果", "未找到匹配项");
    }
}

void SuspendedSearchBox::closeEvent(QCloseEvent* event)
{
    event->ignore();
    hideSearchBox();
}

void SuspendedSearchBox::setFindMode(FindMode mode)
{
    for (int i = 0; i < m_modeCombo->count(); ++i) {
        if (m_modeCombo->itemData(i).value<FindMode>() == mode) {
            m_modeCombo->setCurrentIndex(i);
            break;
        }
    }
}

FindMode SuspendedSearchBox::getCurrentFindMode() const
{
    return m_modeCombo->currentData().value<FindMode>();
}

QString SuspendedSearchBox::getSearchText() const
{
    return m_searchEdit->text().trimmed();
}

void SuspendedSearchBox::showSearchBox()
{
    show();
    m_searchEdit->setFocus();
}

void SuspendedSearchBox::hideSearchBox()
{
    m_searchEdit->clear();
    hideResults();
    hide();
    emit hidden();
}

void SuspendedSearchBox::showResults()
{
    if (m_resultsVisible) return;

    m_resultsVisible = true;
    m_resultList->show();
    setFixedHeight(80 + 300);
}

void SuspendedSearchBox::hideResults()
{
    if (!m_resultsVisible) return;

    m_resultsVisible = false;
    m_resultList->clear();
    m_resultList->hide();
    setFixedHeight(80);
}